#include "CocosPCH.h" 

#include "CoCShapeNode.h"
#include "CoCImageNode.h"

// implementation of CoCShapeNode

CoCShapeNode::CoCShapeNode()
{
}

CoCShapeNode::~CoCShapeNode()
{ 
}

CoCShapeNode* CoCShapeNode::create()
{
    CoCShapeNode* pRet = new CoCShapeNode();
    if (pRet && pRet->init())
    {
        pRet->autorelease();
    }
    else
    {
        CC_SAFE_DELETE(pRet);
    }
    
    return pRet;
}

void CoCShapeNode::setColor(Color4B color)
{
	m_colors = color;
	for(size_t i = 0; i < m_vecImage.size(); i++)
	{
		m_vecImage[i]->setColor(m_colors);
	}
}

void CoCShapeNode::addImage(CoCImageNode *pImage)
{
	addChild(pImage);
	m_vecImage.push_back(pImage);
}

Rect CoCShapeNode::getRect()
{
	
	float fMinX, fMinY, fMaxX, fMaxY;
	Rect rc = Rect::ZERO;
	bool bFirst = true;
    for (size_t i = 0; i < m_vecImage.size(); i++)
	{
		if(m_vecImage[i])
		{
			if(bFirst)
			{
				bFirst = false;
				rc = m_vecImage[i]->getRect();
				fMinX = rc.origin.x;
				fMaxX = rc.origin.x + rc.size.width;
				fMinY = rc.origin.y;
				fMaxY = rc.origin.y + rc.size.height;
			}
			else
			{
				rc = m_vecImage[i]->getRect();
				fMinX = rc.origin.x < fMinX ? rc.origin.x : fMinX;
				fMaxX = rc.origin.x+rc.size.width > fMaxX ? rc.origin.x+rc.size.width : fMaxX;
				fMinY = rc.origin.y < fMinY ? rc.origin.y : fMinY;
				fMaxY = rc.origin.y+rc.size.height > fMaxY ? rc.origin.y+rc.size.height : fMaxY;
			}
		}
	}
	if(bFirst)
	{
		return Rect::ZERO;
	}
	rc.origin.x = fMinX;
	rc.origin.y = fMinY;
	rc.size.width = fMaxX-fMinX;
	rc.size.height = fMaxY-fMinY;
	return rc;
}

std::string CoCShapeNode::SaveScreenshot(const char *pName) 
{ 
	Rect rc = getRect();
    RenderTexture* texture = RenderTexture::create(rc.size.width, rc.size.height); 
    texture->beginWithClear(0, 0, 0, 0, 0, 0); 
	this->setPosition(Vec2(-rc.origin.x, -rc.origin.y)); 
    this->visit(); 
    texture->end(); 

    Director::getInstance()->getRenderer()->render();
    Image* image = texture->newImage();
    if(image->saveToFile(pName, false)) 
    { 
        CCLOG("filePath:%s",pName); 
		delete image;
        return pName; 
    } 
    else 
    { 
        CCLOG("write file error");
    } 
    return "";
}